﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace EliteInfos
{
    public class Client
    {
        private TcpClient _client;

        public delegate void MessageReceivedHandler(string message);

        public event MessageReceivedHandler OnMessageReceived;
        
        public void Connect(String server, Int32 port)
        {
            _client = new TcpClient(server, port);

            // envoi de l'information de connexion à Elite
            NetworkStream stream = _client.GetStream();

            Byte[] data = System.Text.Encoding.ASCII.GetBytes("EliteInfos_Connexion");
            stream.Write(data, 0, data.Length);
        }

        public void Loop()
        {
            try
            {
                while (true)
                {
                    // Ecoute des messages envoyés par Elite
                    NetworkStream stream = _client.GetStream();
                    var data = new Byte[10000];
                    Int32 bytes = stream.Read(data, 0, data.Length);
                    var responseData = System.Text.Encoding.Default.GetString(data, 0, bytes);

                    if (responseData.Equals("/exit"))
                        break;
                    else if (responseData != "")
                        OnMessageReceived(responseData);
                }                
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }

            finally
            {
                _client.Close();
            }
        }
    }
}
